package pers.cz.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: PostGirl-panent
 * @description: MessagePushSocket
 * @author: Cheng Zhi
 * @create: 2021-10-06 22:37
 **/
@ServerEndpoint("/websocket/{userId}")
@Component
public class MessagePushSocketUtils {

    private static Logger log = LoggerFactory.getLogger(MessagePushSocketUtils.class);

    public static final String AUTOUI_MESSAGE = "autoUI";
    public static final String AUTOUI_LOG_MESSAGE = "autoUiLog";

    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    //private static CopyOnWriteArraySet<MessagePushSocketUtils> webSocketSet = new CopyOnWriteArraySet<MessagePushSocketUtils>();
    private static Map<Integer, MessagePushSocketUtils> webSocketMap = new ConcurrentHashMap<Integer, MessagePushSocketUtils>();

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private Integer userId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        this.session = session;
        this.userId = Integer.valueOf(userId);
        //webSocketSet.add(this); // 加入set中
        webSocketMap.put(this.userId, this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        // webSocketSet.remove(this); // 从set中删除
        webSocketMap.remove(userId);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        if (message.contains("HeartCheck")) {
            // 回应
            MessagePushSocketUtils.sendInfo("HeartCheck|Girl",userId  );
        }
        if (log.isDebugEnabled()) {
            log.debug("收到来自"+ userId +"的心跳:" + message);
        }


    }

    /**
     * 发生错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误", error);
    }

    /**
     * 实现服务器主动推送
     */
    public synchronized void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String string, Integer userId) {
        log.info("推送消息到窗口" + string);
        for (MessagePushSocketUtils item : webSocketMap.values()) {
            try {
                if (userId != null && userId > 0) {
                    if (userId.equals(item.userId)) {
                        item.sendMessage(string);
                    }
                } else {
                    // 广播全部
                    item.sendMessage(string);
                }

            } catch (IOException e) {
                log.error("reply message failed!", e);
            }
        }
    }

    /**
     * 不抛异常的发送消息
     * @param msgType
     * @param msg
     * @param userId
     */
    public static void sendMsg(String msgType, String msg, Integer userId) {

        try {
            String type = msgType + "|" + msg;
            sendInfo(type, userId);
        } catch (Exception e) {
            log.error("send message failed!", e);
        }
    }
}
